﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Xml;


namespace ManageInventory
{
    public partial class Form1 : Form
    {
        //Database file path
        string path = Application.StartupPath + "//db.csv";
        //CSV Split string array (database)
        string[] db = null;

        public Form1()
        {
            InitializeComponent();
        }

        #region Load Items From db
        private void Form1_Load(object sender, EventArgs e)
        {
            //Reads database from file
            db = File.ReadAllLines(path);
            for (int i = 0; i < db.Length; i++)
            {
                //Splits items by ',' character (creates cells)
                string[] ItemInfo = db[i].Split(',');
                //Adds each item row with the associated info
                dataGridView1.Rows.Add(ItemInfo[0], ItemInfo[1], ItemInfo[2], ItemInfo[3], ItemInfo[4]);
            }
            CalculateAdvanced();
        }

        #endregion

        #region Calculate Advanced

        void CalculateAdvanced()
        {
            int RowCount = dataGridView1.RowCount;

            //calc TtlCost
            double allAtCost = 0;
            for (int i = 0; i < RowCount; i++)
            {
                DataGridViewRow currentRow = dataGridView1.Rows[i];
                DataGridViewCell ttlCost = currentRow.Cells[5];
                DataGridViewCell qty = currentRow.Cells[2];
                DataGridViewCell cost = currentRow.Cells[3];
                DataGridViewCell price = currentRow.Cells[4];
                double currentTtlCost = System.Convert.ToDouble(qty.Value) * System.Convert.ToDouble(cost.Value);
                ttlCost.Value = currentTtlCost;
                allAtCost = allAtCost + currentTtlCost;

                double currentLeftOver = System.Convert.ToDouble(price.Value) - System.Convert.ToDouble(cost.Value);
                DataGridViewCell profitDollar = currentRow.Cells[9];
                profitDollar.Value = currentLeftOver;
                DataGridViewCell profitPercent = currentRow.Cells[10];
                profitPercent.Value = Math.Round(currentLeftOver / System.Convert.ToDouble(cost.Value), 2);
            }
            //---

            //calc PercentToTotal & ttlAtRetail
            double allAtRetail = 0;
            for (int i = 0; i < RowCount; i++)
            {
                DataGridViewRow currentRow = dataGridView1.Rows[i];
                DataGridViewCell ttlCost = currentRow.Cells[5];
                DataGridViewCell percentToTotal = currentRow.Cells[6];
                DataGridViewCell qty = currentRow.Cells[2];
                DataGridViewCell retailPrice = currentRow.Cells[4];
                DataGridViewCell ttlAtRetail = currentRow.Cells[7];
                double newPercentToTotal = (System.Convert.ToDouble(ttlCost.Value) / allAtCost) * 100;
                percentToTotal.Value = Math.Round(newPercentToTotal, 2);
                double newttlAtRetail = System.Convert.ToDouble(qty.Value) * System.Convert.ToDouble(retailPrice.Value);
                ttlAtRetail.Value = newttlAtRetail;
                allAtRetail = allAtRetail + newttlAtRetail;

            }
            //---
            
            //calc PercentToRetailTtl
            for (int i = 0; i < RowCount; i++)
            {
                DataGridViewRow currentRow = dataGridView1.Rows[i];
                DataGridViewCell ttlAtRetail = currentRow.Cells[7];
                DataGridViewCell PercentToRetailTtl = currentRow.Cells[8];
                double newPercentToRetailTtl = (System.Convert.ToDouble(ttlAtRetail.Value) / allAtRetail) * 100;
                PercentToRetailTtl.Value = Math.Round(newPercentToRetailTtl, 2);
            }
            //---

            //set labells
            label3.Text = String.Format("{0:C}", (allAtRetail - allAtCost));
            label4.Text = Math.Round((((allAtRetail - allAtCost) / allAtRetail) * 100), 2).ToString() + "%";
            label5.Text = String.Format("{0:C}", allAtCost);
            label6.Text = String.Format("{0:C}", allAtRetail);
        }
        #endregion

        #region Save Changes
        void SaveChanges()
        {
            //Saves changes to database
            File.WriteAllText(path, String.Join(Environment.NewLine, newDB()));
        }

        private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //Save toolstrip item
            SaveChanges();
        }

        private string[] newDB()
        {
            //Creates new database from gridview
            try
            {
                string[] Rows = new string[dataGridView1.Rows.Count];
                for (int i = 0; i < Rows.Length; i++)
                {
                    string[] Cells = new string[5];
                    for (int f = 0; f < 5; f++)
                    {
                        Cells[f] = dataGridView1.Rows[i].Cells[f].Value.ToString();
                    }
                    Rows[i] = String.Join(",", Cells);
                }
                return Rows;
            }
            catch
            {
                return new string[0];
            }
        }
        #endregion

        #region Remove Items
        void removeSelectedItems()
        {
            //Removes any selected items
            dataGridView1.Rows.Remove(dataGridView1.Rows[dataGridView1.SelectedCells[0].RowIndex]);
        }

        private void removeBtn_Click(object sender, EventArgs e)
        {
            //Displays remove warning
            if (MessageBox.Show("This will permanently remove the selected item(s) from your inventory. Continue?", "Warning", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                removeSelectedItems();

            }
        }
        #endregion

        #region Confirm Exit
        //Closes the strip tool menu
        private void closeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        //Closes the form
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (String.Join(Environment.NewLine, newDB()) != String.Join(Environment.NewLine, db))
            {
                DialogResult dlgRes = MessageBox.Show("Do you want to save the changes?", "Warning", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
                if (dlgRes == DialogResult.Yes)
                {
        //Gives choice to save before closing
                    SaveChanges();
                    e.Cancel = false;

                }
                else if (dlgRes == DialogResult.No)
                {
                    e.Cancel = false;
                }
                else if (dlgRes == DialogResult.Cancel)
                {
                    e.Cancel = true;
                }
            }
        }
        #endregion

        #region Sensative Edit
        //Removes seected items from menu strip
        private void deleteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            removeSelectedItems();
        }
        //Edits the datagrid view
        private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            if (dataGridView1.CurrentCell.ColumnIndex >= 1)
            {
                TextBox txtEdit = e.Control as TextBox;
                txtEdit.KeyPress += new KeyPressEventHandler(txtEdit_KeyPress);
            }
        }

        void txtEdit_KeyPress(object sender, KeyPressEventArgs e)
        {
            if ("0123456789\b.".IndexOf(e.KeyChar) == -1)
                e.Handled = true;
        }
        //Edits the cells in the database
        private void dataGridView1_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
        {
            if (e.RowIndex == dataGridView1.Rows.Count - 1)
            {
                for (int i = 0; i < dataGridView1.ColumnCount; i++)
                {
                    if (dataGridView1.Rows[e.RowIndex - 1].Cells[i].Value == null)
                    {
                        e.Cancel = true;
                        toolStripStatusLabel1.Text = "Item missing values.";
                    }
                }
            }
        }
        //Tests the data to see if it coralates with the database
        private void dataGridView1_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                DataGridView.HitTestInfo hti = this.dataGridView1.HitTest(e.X, e.Y);
                if (hti.Type == DataGridViewHitTestType.Cell)
                {
                    this.dataGridView1.ClearSelection();
                    this.dataGridView1.Rows[hti.RowIndex].Cells[hti.ColumnIndex].Selected = true;
                    contextMenuStrip1.Show(Cursor.Position);
                }
            }
        }

        #endregion

        #region Column Viewing
        //Toggles how visable the form is
        private void ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            colVisableToogle(sender.ToString());
        }

        void colVisableToogle(string sender)
        {
            ToolStripMenuItem[] list = new ToolStripMenuItem[] { itemDescToolStripMenuItem, stockToolStripMenuItem, qTYOnHandToolStripMenuItem, costToolStripMenuItem, retailPriceToolStripMenuItem, ttlCostToolStripMenuItem, toTtlCostToolStripMenuItem, ttlAtRetailToolStripMenuItem, toTtlRetailToolStripMenuItem, profitMarginToolStripMenuItem, profitMarginToolStripMenuItem1};
            for (int i = 0; i < list.Length; i++)
            {
                if (list[i].Text == sender)
                {
                    if (list[i].Checked)
                    {
                        list[i].Checked = false;
                        dataGridView1.Columns[i].Visible = false;
                    }
                    else
                    {
                        list[i].Checked = true;
                        dataGridView1.Columns[i].Visible = true;
                    }
                }
            }
        }
        #endregion

        #region Edit Item
        //Sends the code when the mouse is clicked
        private void editBtn_Click(object sender, EventArgs e)
        {
            int selectedIndex = 0;
            selectedIndex = dataGridView1.SelectedCells[0].RowIndex;
            dataGridView1.ClearSelection();
            dataGridView1.Rows[selectedIndex].Selected = true;

            EditItem editFrm = new EditItem();
            editFrm.itemInfo = selectedItemInfo();
            editFrm.averageProfit = label4.Text;
            if (editFrm.ShowDialog() == DialogResult.OK)
            {
                for (int i = 0; i < 4; i++)
                {
                    dataGridView1.SelectedRows[0].Cells[i].Value = editFrm.setInfo[i];
                }
                CalculateAdvanced();
            }

        }
        //Says what to do with the selected item
        public string[] selectedItemInfo()
        {

                string[] tmp = new string[5];
                for (int i = 0; i < 5; i++)
                {
                    tmp[i] = dataGridView1.SelectedRows[0].Cells[i].Value.ToString();
                }
                return tmp;

        }

        #endregion

        #region Add Items
        //Adds an item to the database
        private void addBtn_Click(object sender, EventArgs e)
        {

            EditItem editFrm = new EditItem();
            editFrm.addingItem = true;
            editFrm.averageProfit = label4.Text;
            if (editFrm.ShowDialog() == DialogResult.Yes)
            {
                    dataGridView1.Rows.Add(editFrm.getInfo.Split(','));
                    CalculateAdvanced();
            }

        }
        #endregion

        #region Shortcut Keys
        //What is equal to what shortcut key
        private void addItemToolStripMenuItem_Click(object sender, EventArgs e)
        {
            addBtn.PerformClick();
        }

        private void removeItemToolStripMenuItem_Click(object sender, EventArgs e)
        {
            removeBtn.PerformClick();
        }

        private void editItemToolStripMenuItem_Click(object sender, EventArgs e)
        {
            editBtn.PerformClick();
        }

        #endregion

        #region Show Advanced CB
        //Controls all the checkboxes
        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            if (!checkBox1.Checked)
            {
                if (ttlCostToolStripMenuItem.Checked) ttlCostToolStripMenuItem.PerformClick();
                if (toTtlCostToolStripMenuItem.Checked) toTtlCostToolStripMenuItem.PerformClick();
                if (ttlAtRetailToolStripMenuItem.Checked) ttlAtRetailToolStripMenuItem.PerformClick();
                if (toTtlRetailToolStripMenuItem.Checked) toTtlRetailToolStripMenuItem.PerformClick();
                if (profitMarginToolStripMenuItem.Checked) profitMarginToolStripMenuItem.PerformClick();
                if (profitMarginToolStripMenuItem1.Checked) profitMarginToolStripMenuItem1.PerformClick();
            }
            else
            {
                if (!ttlCostToolStripMenuItem.Checked) ttlCostToolStripMenuItem.PerformClick();
                if (!toTtlCostToolStripMenuItem.Checked) toTtlCostToolStripMenuItem.PerformClick();
                if (!ttlAtRetailToolStripMenuItem.Checked) ttlAtRetailToolStripMenuItem.PerformClick();
                if (!toTtlRetailToolStripMenuItem.Checked) toTtlRetailToolStripMenuItem.PerformClick();
                if (!profitMarginToolStripMenuItem.Checked) profitMarginToolStripMenuItem.PerformClick();
                if (!profitMarginToolStripMenuItem1.Checked) profitMarginToolStripMenuItem1.PerformClick();
            }
        }

        #endregion

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

    }
}
